﻿using System;
using CoreLibrary.Service;
using NLog;
using WebService.Security;

namespace WebService.Service {

    public abstract class AbstractService {

        protected static T Locate<T>() where T: class, IService {
            return Services.Locate<T>();
        }

        protected static T Locate<T>(string name) where T : class, IService {
            return Services.Locate<T>(name);
        }

        protected void Run(string passport, Action<UserToken> func) {
            try {
                var token = PassportUtil.ReadPassport(passport);
                func.Invoke(token);
            } 
            catch (Exception exception) {
                LogManager.GetCurrentClassLogger().ErrorException(exception.Message, exception);
                throw ServiceErrors.CreateException(ErrorCode.InvalidRequest, "Error", exception.Message);
            }
        }

        protected T Run<T>(string passport, Func<UserToken, T> func) {
            try {
                var token = PassportUtil.ReadPassport(passport);
                return func.Invoke(token);
            }
            catch (Exception exception) {
                LogManager.GetCurrentClassLogger().ErrorException(exception.Message,exception);
                throw ServiceErrors.CreateException(ErrorCode.InvalidRequest, "Error", exception.Message);
            }
        }

    }
}